import React, { useState, useEffect } from "react";
import styles from "./index.module.less";

export const CountdownTimer = ({ timestamp }) => {
  const calculateTimeLeft = (endTime) => {
    const now = new Date().getTime();
    const remainingMilliseconds = Math.max(0, endTime - now);

    return {
      hours: Math.floor(remainingMilliseconds / 3600000),
      minutes: Math.floor((remainingMilliseconds % 3600000) / 60000),
      seconds: Math.floor((remainingMilliseconds % 60000) / 1000),
    };
  };

  const [timeLeft, setTimeLeft] = useState(calculateTimeLeft(timestamp));

  useEffect(() => {
    const timer = setInterval(() => {
      setTimeLeft(calculateTimeLeft(timestamp));
    }, 1000);

    return () => {
      clearInterval(timer);
    };
  }, [timestamp]);

  const formatTime = (time) => String(time).padStart(2, "0");

  return (
    <div className={styles.countdownTimer}>
      倒计时
      <span>{formatTime(timeLeft.hours)}</span>:
      <span>{formatTime(timeLeft.minutes)}</span>:
      <span>{formatTime(timeLeft.seconds)}</span>
    </div>
  );
};
